﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MonoDevelop.Core;
using MonoDevelop.Projects;
using theeg.DependencyAnalysis.CommonAddin.Models;

namespace theeg.DependencyAnalysis.MonoAddin
{
    public class MonoSolution : ISolution
    {
        private Solution _solution;

        public Action BuildFinished { get; set; }

        public string FileName { get; private set; }

        public IList<IProject> Projects { get; private set; }

        public void Refresh()
        {
            _solution = MonoDevelop.Ide.IdeApp.Workspace.GetAllSolutions().FirstOrDefault();
            if (_solution == null)
            {
                return;
            }
            FileName = _solution.FileName;
            var solutionProjects = _solution.GetAllProjects().ToList();
            var projects = (from project in solutionProjects
                            where MonoProject.IsClrProject(project)
                            orderby project.Name
                            select new MonoProject(project) { Name = project.Name, IsSelected = true }).Cast<IProject>().ToList();

            Projects = projects;
        }

        public void Build()
        {
            var buildTask = MonoDevelop.Ide.IdeApp.Workspace.Build();
            buildTask.WaitForCompleted();
            var buildFinished = BuildFinished;
            if (buildFinished != null)
            {
                buildFinished();
            }
        }
    }
}
